import {
  debounce
} from "../../utils/index"
import {
  ApihandleById,
  Apieventrecord,
  ApiUpload,
  ApiEventUploadFile,
  ApiUser,
  ApiAllocation,
  ApiReview,
  ApiPhone
} from "../../api/index"
import Dialog from '@vant/weapp/dialog/dialog';
const app = getApp()
let {
  baseUrl,
  commonUpdate,
  commonUpload
} = app.globalData
let userInfo = wx.getStorageSync('userInfo')
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    id: {
      type: String,
    },
    event_no: {
      type: String
    },
    prepeoples: {
      type: Array,
    },
    detailData: {

    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    ChangePick: '',
    columns: ['轻伤', '重伤', '死亡'],
    showCasualty: false,
    showLog: false,
    actions: [{
        name: '拍照',
      },
      {
        name: '录视频',
      },
    ],
    cameraHeight: '',
    cameraWidth: '',
    image1Src: '',
    videoSrc: '',
    show: false,
    showProcessor: false,
    peoples: [],
    num: 0,
    showDialog: false,
    query: {
      // 处理结果
      result: "",
      casualty: '',
      // 涉案人数
      associate_number: '',
      financial_loss: '',
      total_value: '',
      financial_type: '',
      file: [],
      status: "3",
    },
    state: "",
    audit_note: "",
    autosize: {
      maxHeight: 200,
      minHeight: 150
    },
    errorMessage: "",
    auditMessage: "",
    btnLoaading: false,
    fileList: [],
    photoLink: '',
    videoLink: '',
    baseUrl,
    // 存储所拍照的信息
    photoDataAndVideoData: {},
    userInfo: userInfo
  },




  // onload() {
  //   ApiPhone().then
  // },
  /**
   * 组件的方法列表
   */
  methods: {
    onMyevent(e) {
      // console.log(e)
      // console.log(this.data.peoples, e.detail.index)
      let people = this.data.peoples
      people[e.detail.index] = (e.detail.detail)
      this.setData({
        peoples: this.data.peoples
      })
    },




    stop() {},
    handleFile() {
      wx.navigateTo({
        url: `/pages/orderInsert/index`,
      })
    },

    onCloseLog() {
      this.setData({
        showLog: false
      });
    },

    onSelectLog(event) {
      console.log(event)
      if (event.detail.name == '拍照') {
        this.photoCapture()
        return
      } else if (event.detail.name == '录视频') {
        this.videoCapture()
        return
      }
    },



    //拍摄照片
    photoCapture() {
      let query = {
        count: 1,
        mediaType: ['image'],
        sourceType: ['camera'],
        camera: 'back',
      }
      this.photoCommon(query, '照片')
    },



    
    //拍摄视频
    videoCapture() {
      let query = {
        count: 1,
        mediaType: ['video'],
        sourceType: ['camera'],
        maxDuration: 60,
        camera: 'back',
      }
      this.photoCommon(query, '视频')
    },
    photoCommon(query, val) {
      let that = this
      let json = JSON
      wx.chooseMedia({
        ...query,
        success(res) {
          that.setData({
            type: res.type
          })
          wx.showLoading({
            title: `正在上传${val}`,
            mask: true
          })
          wx.uploadFile({
            url: baseUrl + commonUpdate,
            filePath: res.tempFiles[0].tempFilePath,
            header: {
              Authorization: 'Bearer ' + wx.getStorageSync('token')
            },
            name: 'file',
            success(res) {
              that.setData({
                showDialog: true
              })
              let baseUrlLink = baseUrl + commonUpload + json.parse(res.data).data.path
              if (val == '照片') {
                that.setData({
                  photoLink: baseUrlLink
                })
              } else {
                that.setData({
                  videoLink: baseUrlLink
                })
              }
              that.setData({
                photoDataAndVideoData: {
                  file_type: that.data.type,
                  file_path: json.parse(res.data).data.path,
                  event_record_id: that.id
                }
              })
              wx.showToast({
                title: "上传成功",
              })
            },
            fail(err) {
              console.log(err)
            }
          })
        },
        // fail(res) {
        //   console.log(res)
        //   console.log('图片拍摄失败')
        // }
      })
    },
    // 文件上传
    afterRead: function (event) {
      console.log(event.file)
      let that = this
      let json = JSON
      const {
        file,
      } = event.detail
      this.setData({
        type: file.type
      })

      wx.showLoading({
        title: '上传中',
        mask: true
      })
      wx.uploadFile({
        url: baseUrl + commonUpdate,
        filePath: file.url,
        name: 'file',
        header: {
          Authorization: 'Bearer ' + wx.getStorageSync('token')
        },
        success(res) {
          // 展示文件数据
          that.data.fileList.push({
            url: baseUrl + commonUpload + json.parse(res.data).data.path,
          })
          that.setData({
            fileList: that.data.fileList
          })
          //传值 
          that.data.query.file.push({
            file_name: json.parse(res.data).data.name,
            file_path: json.parse(res.data).data.path,
            file_type: that.data.type
          })
          wx.showToast({
            title: '上传文件成功',
          })
        }
      })
    },

    // 弹窗提交事件
    dialogConfirm() {
      console.log(this.data.event_no, this.data.photoDataAndVideoData)

      ApiEventUploadFile(this.data.photoDataAndVideoData).then(res => {
        if (res.code == 200) {
          wx.showToast({
            title: "提交成功",
          })
          this.setData({
            showDialog: false
          })
        }
      })
    },
    dialogCancel() {
      this.setData({
        showDialog: false
      })
    },

    // 删除照片
    handleDelete(event) {
      this.data.fileList.splice(event.detail.index, 1)
      this.data.query.file.splice(event.detail.index, 1)
      this.setData({
        fileList: this.data.fileList,
        "query.file": this.data.query.file
      })
    },


    // 处理警情
    onOpen(e) {
      this.setData({
        show: true,
        //深拷贝数据
        // peoples: JSON.parse(JSON.stringify(this.data.prepeoples))
      })

    },

    // 分配处理人
    OnIstributionProcessor() {
      this.setData({
        showProcessor: true,
        //深拷贝数据
        // peoples: JSON.parse(JSON.stringify(this.data.prepeoples))
      })
    },

    // 审核警情
    onIsProcessor() {
      this.setData({
        showisProcessor: true,
        audit_note: ''
        //深拷贝数据
        // peoples: JSON.parse(JSON.stringify(this.data.prepeoples))
      })
    },


    // 分配人员点击
    ProcessorClick() {
      this.setData({
        showCasualty: true,
      })
      ApiUser({
        department_ids: this.data.detailData.department_id,
        allPage: 2
      }).then(res => {
        let userName = []
        res.data.forEach(item => {
          // this.setData({
          //   ProcessorUser: res.data
          // })
          // userName.push(item.name + ' ' + item.department_name + ' ' + item.id)
          userName.push({
            values: item.id,
            name: item.name + ' ' + item.department_name
          })
        })
        // console.log(userName);
        this.setData({
          columns: res.data
        })
      })
    },



    onChangePick(e) {
      this.setData({
        ChangePick: e.detail.value
      })
      // console.log(e.detail.value)
    },
    casualtyClick() {
      this.setData({
        showCasualty: true,
        columns: ['轻伤', '重伤', '死亡']
      })
    },
    onChange(e) {
      // if (e.detail === this.data.state) return
      this.setData({
        "query.status": e.detail,
      })
    },
    onConfirm(e) {
      console.log(e)
      if (!e.detail.value.id) {
        console.log('1')
        this.setData({
          "query.casualty": e.detail.value,
          showCasualty: false
        })
      } else {
        console.log('2')
        this.setData({
          "query.handler_id": e.detail.value.id,
          "query.handler_name": e.detail.value.name + ' ' + e.detail.value.department_name,
          showCasualty: false
        })

      }

    },
    onCancel() {
      this.setData({
        showCasualty: false
      })
    },

    onInput(e) {
      const name = `query.${e.currentTarget.dataset.t}`
      this.setData({
        // "query.review_result": e.detail
        [name]: e.detail
      })
    },
    onClose() {

      this.setData({
        show: false,
        showProcessor: false,
        showisProcessor: false,
        columns: [],
        query: {
          // 处理结果
          result: "",
          casualty: '',
          // 涉案人数
          associate_number: '',
          financial_loss: '',
          total_value: '',
          financial_type: '',
          file: [],
          status: '3',
          review_result: ''
        },
        peoples: [],
      });

      console.log(this.data.peoples)
    },
    onCloseProcessor() {
      this.setData({
        show: false,
        showProcessor: false,
        showisProcessor: false,
        columns: [],
        query: {
          // 处理结果
          result: "",
          casualty: '',
          // 涉案人数
          associate_number: '',
          financial_loss: '',
          total_value: '',
          financial_type: '',
          file: []
        },
        peoples: [],
      });
    },
    onCloseAudit() {
      this.setData({
        show: false,
        showProcessor: false,
        showisProcessor: false,
        columns: [],
        query: {
          // 处理结果
          result: "",
          casualty: '',
          // 涉案人数
          associate_number: '',
          financial_loss: '',
          total_value: '',
          financial_type: '',
          file: [],
          handler_id: ''
        },
        peoples: [],
      });
    },


    onSubmit: debounce(function (e) {
      // 分配人
      console.log(this.data.detailData)

      // 找到最后一个空格的位置

      if (e.currentTarget.dataset.value == 'people') {
        if (!this.data.query.handler_id) {
          this.setData({
            ProcessorMessage: '请选择分配人员'
          })
          return;
        }
        // let lastIndex = this.data.ChangePick.lastIndexOf(" ");
        // let handler_id = this.data.ChangePick.substring(lastIndex + 1);
        ApiAllocation(this.data.detailData.id, {
          handler_id: this.data.query.handler_id
        }).then(res => {
          this.triggerEvent("submit", {
            data: 'success',
            callBack: (flag) => {
              if (flag) {
                this.onCloseProcessor()
              }
            }
          })
        })
      }

      //  审核人
      if (e.currentTarget.dataset.value == 'audit') {
        if (!this.data.query.review_result) {
          this.setData({
            auditMessage: '请输入意见！'
          })
          return;
        }

        ApiReview(this.data.detailData.id, this.data.query).then(res => {
          this.triggerEvent("submit", {
            data: 'success',
            callBack: (flag) => {
              if (flag) {
                this.onCloseAudit()
              }
            }
          })
        })
      }

      if (this.data.query.result && this.data.query.result.length > 0) {
        ApihandleById({
          ...this.data.query,
          peoples: this.data.peoples,
        }, this.id).then(res => {
          if (res.code == 200) {
            this.setData({
              fileList: [],
              "query.file": []
            })
            //回调函数
            this.triggerEvent("submit", {
              data: 'success',
              callBack: (flag) => {
                if (flag) {
                  this.onClose()
                }
              }
            })
          }
        })
      } else {
        this.setData({
          errorMessage: "请输入处理结果！"
        })
      }

      // 调用函数进行处理值操作

      // if((this.data.isRule || this.data.state === 'draft') && !this.data.audit_note){
      //   this.setData({
      //     errorMessage: "请输入审核意见！"
      //   })
      //   return 
      // }
      // this.setData({
      //   btnLoaading: true
      // })
      // const ops = {
      //   audit_note: this.data.audit_note,
      //   state: this.data.state,
      // }
      // this.triggerEvent("submit",{
      //   data: ops,
      //   callBack: (flag) => {
      //     if(flag){
      //       this.onClose()
      //     }
      //     this.setData({
      //       btnLoaading: false,
      //     })
      //   }
      // })
    }, 500, true),














  }
})